package com.example.emergencyattempt01.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import com.example.emergencyattempt01.R;

import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.ServerMessage;
import com.example.emergencyattempt01.user.User;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import android.os.Handler;
import org.json.JSONException;
import org.json.JSONObject;

public class St_CheckingAdapter extends BaseAdapter {
    Context context;
    List<Map<String,Object>> itemList;
    User student;
    ViewHolder viewHolder;

    Handler handler =new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int position=(int)msg.obj;
           switch (msg.what)
           {
               case CANCEL_SUCCESS:
                   Toast.makeText(context,"已取消申请",Toast.LENGTH_SHORT).show();
                   itemList.remove(position);
                   break;
               case CANCEL_FAIL:

                   break;
               case CONFIRM_SUCCESS:
                   Toast.makeText(context,"已再次申请",Toast.LENGTH_SHORT).show();
                   itemList.remove(position);
                   break;
               case CONFIRM_FAIL:
                   Toast.makeText(context,"网络错误...",Toast.LENGTH_SHORT).show();
                   break;
           }
            notifyDataSetChanged();
        }
    };
    final int CANCEL_SUCCESS=0x001;
    final int CANCEL_FAIL=0x002;
    final int CONFIRM_SUCCESS=0x003;
    final int CONFIRM_FAIL=0x004;



    public St_CheckingAdapter(Context context, List<Map<String, Object>> itemList, User student) {
        this.context = context;
        this.itemList = itemList;
        this.student = student;
    }
    class ViewHolder
    {
        TextView bidField;
        TextView lidField;
        TextView uidField;
        TextView userNameField;
        TextView identityField;
        TextView ownBooksField;
        TextView bookNameField;
        TextView ISBNField;
        TextView borrowTimeField;

        Button refuse;
        Button permit;

        ImageView shapeMarker;

        TextView textMarker;

        TextView checkingTimeType;

        TextView waiting;

        ImageView notPass;
    }
    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return (long)itemList.get(position).get("bid");
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        if(convertView==null)
        {
            viewHolder=new ViewHolder();
            convertView=inflater.inflate(R.layout.st_checking_item,null);
            // 初始化view
            viewHolder.bidField=convertView.findViewById(R.id.st_checking_bid);
            viewHolder.uidField=convertView.findViewById(R.id.st_checking_uid);
            viewHolder.lidField=convertView.findViewById(R.id.st_checking_lid);
            viewHolder.bookNameField=convertView.findViewById(R.id.st_checking_bookName);
            viewHolder.borrowTimeField=convertView.findViewById(R.id.st_checking_borrowTime);
            viewHolder.userNameField=convertView.findViewById(R.id.st_checking_userName);
            viewHolder.identityField=convertView.findViewById(R.id.st_checking_identity);
            viewHolder.ownBooksField=convertView.findViewById(R.id.st_checking_ownBooks);
            viewHolder.ISBNField=convertView.findViewById(R.id.st_checking_ISBN);
            viewHolder.shapeMarker=convertView.findViewById(R.id.st_checking_shape_marker);
            viewHolder.textMarker=convertView.findViewById(R.id.st_checking_text_marker);
            viewHolder.checkingTimeType=convertView.findViewById(R.id.st_checking_time_type);

            viewHolder.permit=convertView.findViewById(R.id.st_checking_permit);
            viewHolder.refuse=convertView.findViewById(R.id.st_checking_refuse);
            viewHolder.waiting=convertView.findViewById(R.id.st_checking_waiting);
            viewHolder.notPass=convertView.findViewById(R.id.st_not_pass);
            convertView.setTag(viewHolder);
        }
        else
        {
           viewHolder=(ViewHolder)convertView.getTag();
        }

        // 设值
        final long bid;
        long lid;
        long uid;
        String userName;
        String identity;
        String bookName;
        final int ownBooks;
        String ISBN;
        long borrowTime;

        String borrowIsConfirmed;

        final String returnIsRequested;
        final String returnIsConfirmed;

        final String continueIsRequested;
        String continueIsConfirmed;
        uid=(long)itemList.get(position).get("uid");
        bid=(long)itemList.get(position).get("bid");
        lid=(long)itemList.get(position).get("lid");

        borrowTime=(long)itemList.get(position).get("borrowTime");

        userName=(String)itemList.get(position).get("userName");
        identity=(String)itemList.get(position).get("identity");
        bookName=(String)itemList.get(position).get("bookName");
        ownBooks=(int)itemList.get(position).get("ownBooks");
        ISBN=(String)itemList.get(position).get("ISBN");

        borrowIsConfirmed=(String)itemList.get(position).get("borrowIsConfirmed");

        returnIsRequested=(String)itemList.get(position).get("returnIsRequested");
        returnIsConfirmed=(String)itemList.get(position).get("returnIsConfirmed");

        continueIsRequested=(String)itemList.get(position).get("continueIsRequested");
        continueIsConfirmed=(String)itemList.get(position).get("continueIsConfirmed");

        // 对单纯的文字部分设值
        viewHolder.uidField.setText("uid:"+uid);
        viewHolder.bidField.setText("借阅号:"+bid);
        viewHolder.lidField.setText("馆藏号:"+lid);
        viewHolder.userNameField.setText(userName);
        viewHolder.identityField.setText(identity);
        viewHolder.bookNameField.setText(bookName);
        if(ownBooks<=5)
            viewHolder.ownBooksField.setText(ownBooks+"本");
        else
            viewHolder.ownBooksField.setText("5本");
        viewHolder.ISBNField.setText(ISBN);

        // 对时间进行一个处理
        String borrowTimeDisplay=millisToString(borrowTime);
        viewHolder.borrowTimeField.setText(borrowTimeDisplay);
        // 处理特殊显示情况
        if(!returnIsRequested.equals("已请求")&&!continueIsRequested.equals("已请求"))
        // 表示借阅请求
        {
            viewHolder.checkingTimeType.setText("申请时间");
            viewHolder.shapeMarker.setImageResource(R.drawable.blue_circle);
            viewHolder.textMarker.setText("借");
        }
        // 表示还书或者续借请求
        else
        {
            viewHolder.checkingTimeType.setText("借阅时间");
            // 此况下，还书与续借只能二者择其一，属于平行分支关系
            if(returnIsRequested.equals("已请求"))
            {
                viewHolder.shapeMarker.setImageResource(R.drawable.red_circle);
                viewHolder.textMarker.setText("还");
            }
            else if(continueIsRequested.equals("已请求"))
            {
                viewHolder.shapeMarker.setImageResource(R.drawable.orange_circle);
                viewHolder.textMarker.setText("续");
            }
        }
        // 如果已经回应了，隐藏加载标签,添加事件监听
        if(borrowIsConfirmed.equals("已拒绝")||(!returnIsConfirmed.equals("待审核")||!continueIsConfirmed.equals("待审核")))
        {
            viewHolder.notPass.setVisibility(View.VISIBLE);
            viewHolder.waiting.setVisibility(View.GONE);
            viewHolder.refuse.setVisibility(View.VISIBLE);
            viewHolder.permit.setVisibility(View.VISIBLE);
            // 设置取消监听
            viewHolder.refuse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder=new AlertDialog.Builder(context);
                    builder.setMessage("确定要取消请求吗？");
                    builder.setNegativeButton("算了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("当然", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new Thread()
                            {
                                @Override
                                public void run() {
                                    try
                                    {
                                        JSONObject object=new JSONObject();
                                        object.put("bid",bid);
                                        String toServer=String.valueOf(object);
                                        ServerMessage serverMessage=null;
                                        // 要判断这是哪种申请，然后调用不同的服务
                                        if(!returnIsRequested.equals("已请求")&&!continueIsRequested.equals("已请求"))// 取消借阅
                                        {
                                            serverMessage=NetWorkUtils.getInstance().create(toServer,"/cancel_borrow_request");
                                        }
                                        else
                                        {
                                            if(returnIsRequested.equals("已请求"))
                                            {
                                                serverMessage=NetWorkUtils.getInstance().create(toServer,"/return_book_cancel");
                                            }
                                            else if(continueIsRequested.equals("已请求"))
                                            {
                                                serverMessage=NetWorkUtils.getInstance().create(toServer,"/continue_cancel");
                                            }
                                        }
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            Message message=new Message();
                                            message.what=CANCEL_SUCCESS;
                                            message.obj=position;
                                            handler.sendMessage(message);
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=CANCEL_FAIL;
                                            message.obj=position;
                                            handler.sendMessage(message);
                                        }

                                    }catch (JSONException e){e.printStackTrace();}
                                    catch (IOException e){e.printStackTrace();
                                        Message message=new Message();
                                        message.what=CANCEL_FAIL;
                                        message.obj=position;
                                        handler.sendMessage(message);}
                                }
                            }.start();
                        }
                    });
                   builder.create().show();
                }
            });


            viewHolder.permit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder=new AlertDialog.Builder(context);
                    builder.setMessage("确定要再次申请吗？");
                    builder.setNegativeButton("算了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("当然", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new Thread()
                            {
                                @Override
                                public void run() {
                                    try
                                    {
                                        JSONObject object=new JSONObject();
                                        object.put("bid",bid);
                                        String toServer=String.valueOf(object);
                                        ServerMessage serverMessage=null;
                                        // 要判断这是哪种申请，然后调用不同的服务
                                        if(!returnIsRequested.equals("已请求")&&!continueIsRequested.equals("已请求"))// 再次借阅
                                        {
                                            serverMessage=NetWorkUtils.getInstance().create(toServer,"/borrow_book_again");
                                        }
                                        else
                                        {
                                            if(returnIsRequested.equals("已请求"))
                                            {
                                                serverMessage=NetWorkUtils.getInstance().create(toServer,"/return_book_request");
                                            }
                                            else if(continueIsRequested.equals("已请求"))
                                            {
                                                serverMessage=NetWorkUtils.getInstance().create(toServer,"/continue_request");
                                            }
                                        }
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            Message message=new Message();
                                            message.what=CONFIRM_SUCCESS;
                                            message.obj=position;
                                            handler.sendMessage(message);
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=CONFIRM_FAIL;
                                            message.obj=position;
                                            handler.sendMessage(message);
                                        }

                                    }catch (JSONException e){e.printStackTrace();}
                                    catch (IOException e){e.printStackTrace();
                                        Message message=new Message();
                                        message.what=CONFIRM_FAIL;
                                        message.obj=position;
                                        handler.sendMessage(message);}
                                }
                            }.start();
                        }
                    });
                   builder.create().show();
                }
            });
        }
        else// 否则把两个功能按钮给去了
        {
            viewHolder.notPass.setVisibility(View.GONE);
            viewHolder.waiting.setVisibility(View.VISIBLE);
            viewHolder.refuse.setVisibility(View.GONE);
            viewHolder.permit.setVisibility(View.GONE);
        }

        return convertView;
    }

    private String millisToString(long timeInMillis) {
        //新建一个calendar对象帮助转化出年月日时分秒
        Calendar calendar=Calendar.getInstance();
        calendar.setTimeInMillis(timeInMillis);
        /**
         * calendar中月份是从0起的
         */
        String year=unify( calendar.get(Calendar.YEAR));
        String month=unify( calendar.get(Calendar.MONTH)+1);
        String day=unify( calendar.get(Calendar.DATE));
        String hour=unify( calendar.get(Calendar.HOUR_OF_DAY));
        String minute=unify( calendar.get(Calendar.MINUTE));
        String second=unify( calendar.get(Calendar.SECOND));

        String target=year+"/"+month+"/"+day+"  "+hour+":"+minute+":"+second;
        return  target;
    }
    private String unify(int num)
    {
        String target=null;
        if(num<10)
        {
            target="0"+num;
        }
        else
            target=""+num;
        return target;
    }
}
